package com.haiyou.data.common.persister.mysql.persister.roll;

import java.io.Serializable;
import java.util.List;

import com.google.common.collect.Lists;
import com.haiyou.common.util.mysql.BatchUtils;
import com.haiyou.data.common.persister.mysql.help.DatabaseHelper;
import com.haiyou.data.common.persister.mysql.persister.PreparedPersister;
import com.haiyou.data.common.persister.mysql.help.TableHelper;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: 滚表持久器 需要更新的数据使用
 * @author xingyuan
 * @date 2022年2月11日 上午10:25:44
 */
@Slf4j
public class RollPreparedPersister<Id extends Serializable & Comparable<Id>, E extends RollEntity<Id>>
		extends PreparedPersister<Id, E> {

	@Override
	public void insertOrUpdate(Iterable<? extends E> iterable) {
		
		checkRollAndIncrTableUpdate();
		//列表转换map
		MyMap<Id, E> map = toMap(iterable);
		
		DatabaseHelper.matchedDatabases(databaseMeta, map.keySet())
				.forEach((db, dbids) -> {
			try {
				TableHelper.matchedRollTables(tableMeta, map.getAll(dbids))
					.forEach((tab, entitys) -> {
					List<E> values = (List<E>) Lists.newArrayList(entitys);
					int size = values.size();
					if (size <= sqlBatchNum()) {
						batchInsertOrUpdate(db, tab, values);
					} else {
						BatchUtils.toLists(values, sqlBatchNum()).forEach(list -> batchInsertOrUpdate(db, tab, list));
					}
				});
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
		});
	}

	@Override
	public void replace(Iterable<? extends E> iterable) {
		checkRollAndIncrTableUpdate();

		MyMap<Id, E> map = toMap(iterable);
		
		DatabaseHelper.matchedDatabases(databaseMeta, map.keySet())
		.forEach((db, dbids) -> {
			try {
				TableHelper.matchedRollTables(tableMeta, map.getAll(dbids))
					.forEach((tab, entitys) -> {
					List<E> values = (List<E>) Lists.newArrayList(entitys);
					int size = values.size();
					if (size <= sqlBatchNum()) {
						batchReplace(db, tab, values);
					} else {
						BatchUtils.toLists(values, sqlBatchNum()).forEach(list -> batchReplace(db, tab, list));
					}
				});
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
		});
		
		
	}

	@Override
	public void update(Iterable<? extends E> iterable) {
		checkRollAndIncrTableUpdate();

		MyMap<Id, E> map = toMap(iterable);
	
		DatabaseHelper.matchedDatabases(databaseMeta, map.keySet())
		.forEach((db, dbids) -> {
			try {
				TableHelper.matchedRollTables(tableMeta, map.getAll(dbids))
					.forEach((tab, entitys) -> {
					List<E> values = (List<E>) Lists.newArrayList(entitys);
					int size = values.size();
					if (size <= sqlBatchNum()) {
						batchUpdate(db, tab, values);
					} else {
						BatchUtils.toLists(values, sqlBatchNum()).forEach(list -> batchUpdate(db, tab, list));
					}
				});
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
		});
	}

	
	
	
	
}
